package com.whq.common.encrypt;

/**
 * 
 * 将二进制数据转化为十六进制字符串
 * 
 * @author wanghuaiqiang 2009-11-24
 *
 */
public final class ByteArrayToFromHexDigits {
	public ByteArrayToFromHexDigits() {
	}

	public static String bytesToHexString(byte abyte0[]) {
		if (abyte0 == null || abyte0.length == 0)
			throw new IllegalArgumentException("argument null or zero length");
		StringBuffer stringbuffer = new StringBuffer(abyte0.length * 2);
		for (int i = 0; i < abyte0.length; i++) {
			stringbuffer.insert(i * 2, chars[abyte0[i] >> 4 & 0xf]);
			stringbuffer.insert(i * 2 + 1, chars[abyte0[i] & 0xf]);
		}

		return stringbuffer.toString();
	}

	private static byte hexCharToByte(char c) throws IllegalArgumentException {
		if (c < '0' || c < 'A' && c > 'F' && c < 'a' && c > 'f')
			throw new IllegalArgumentException("not a hex digit");
		if (c > '9') {
			if (c > 'F')
				return (byte) ((c - 97) + 10 & 0xf);
			else
				return (byte) ((c - 65) + 10 & 0xf);
		} else {
			return (byte) (c - 48 & 0xf);
		}
	}

	public static byte[] hexStringToBytes(String s)
			throws IllegalArgumentException {
		if (s == null)
			throw new IllegalArgumentException("parameter cannot be null");
		if (s.length() == 0)
			throw new IllegalArgumentException(
					"parameter cannot be zero length");
		if ((s.length() & 1) != 0)
			throw new IllegalArgumentException("odd length string");
		byte abyte0[] = new byte[s.length() / 2];
		for (int i = 0; i < s.length(); i += 2)
			abyte0[i / 2] = (byte) ((hexCharToByte(s.charAt(i)) << 4) + hexCharToByte(s
					.charAt(i + 1)));

		return abyte0;
	}

	private static final char chars[] = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
//	private static final boolean debug = false;

}